package com.sanjiahantang.youjiarole.module.goods.views.impl;

import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiarole.R;
import com.sanjiahantang.youjiarole.base.BaseMvpActivity;
import com.sanjiahantang.youjiarole.base.BaseView;
import com.sanjiahantang.youjiarole.config.ConfigValue;
import com.sanjiahantang.youjiarole.module.common.views.impl.MainActivity;
import com.sanjiahantang.youjiarole.module.goods.adapters.GoodsInfoAdapter;
import com.sanjiahantang.youjiarole.module.goods.beans.GoodsBean;
import com.sanjiahantang.youjiarole.module.goods.beans.GoodsListBean;
import com.sanjiahantang.youjiarole.module.goods.presenters.GoodsPresenter;
import com.sanjiahantang.youjiarole.module.goods.views.GoodsView;
import com.sanjiahantang.youjiarole.module.login.views.impl.LoginActivity;
import com.sanjiahantang.youjiarole.module.match.beans.MatchBean;
import com.sanjiahantang.youjiarole.umengshare.UmengShareManager;
import com.sanjiahantang.youjiarole.utils.CheckUtil;

import java.util.List;

import q.rorbin.badgeview.QBadgeView;


/**
 * Created by zy on 2017/8/22.
 */

public class GoodsDetailActivity extends BaseMvpActivity<GoodsView, GoodsPresenter> implements GoodsView, View.OnClickListener {

    private RecyclerView recyclerView;
    private View titleView,titleRoot, btn_buy, btn_addCart, btn_add, btn_similar;

    private RadioButton rbGoods,rbEvaluate,rbInfo,rbRecommend;
    private LinearLayoutManager layoutManager;
    private int goodsID;
    private String goodsadd;
    private TextView txtCart, txt_collection;
    private QBadgeView messageQbv;
    private SwipeRefreshLayout refreshLayout;
    private ImageView ivCart;
    private String findsimilar;
    private GoodsInfoAdapter adapter;
    private int d100;
    private boolean canPull;

    @Override
    public GoodsPresenter initPresenter() {
        return new GoodsPresenter();
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_goods_detail);
        recyclerView = (RecyclerView) $this.findViewById(R.id.rvGoodsInfo);
        d100 = Utils.dip2px($this,100);
        titleView = $this.findViewById(R.id.titleLayout);
        titleRoot = titleView.findViewById(R.id.rootView);
        initTitle();
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refreshLayout);
        ivCart = (ImageView) findViewById(R.id.ivCart);

        btn_add = findViewById(R.id.btn_add);
        txtCart = (TextView) findViewById(R.id.txtCart);
        txt_collection = (TextView) findViewById(R.id.txt_collection);
        btn_similar = findViewById(R.id.btn_similar);
        btn_similar.setOnClickListener(this);
        goodsID = getIntent().getIntExtra("goodsId", 0);
        goodsadd = getIntent().getStringExtra("Add");//传入增项type
        findsimilar = getIntent().getStringExtra("FIND");


        rbGoods = (RadioButton) findViewById(R.id.rbGoods);
        rbEvaluate = (RadioButton) findViewById(R.id.rbEvaluate);
        rbInfo = (RadioButton) findViewById(R.id.rbInfo);
        rbRecommend = (RadioButton) findViewById(R.id.rbRecommend);


        rbGoods.setOnClickListener(this);
        rbEvaluate.setOnClickListener(this);
        rbInfo.setOnClickListener(this);
        rbRecommend.setOnClickListener(this);

        findViewById(R.id.flGoods).setOnClickListener(this);
        findViewById(R.id.flEvaluate).setOnClickListener(this);
        findViewById(R.id.flInfo).setOnClickListener(this);
        findViewById(R.id.flRecommend).setOnClickListener(this);

        if (goodsadd != null) {
            findViewById(R.id.btn_addCart).setVisibility(View.GONE);
            findViewById(R.id.btn_buy).setVisibility(View.GONE);
            findViewById(R.id.vCart).setVisibility(View.GONE);
            findViewById(R.id.vCollection).setVisibility(View.GONE);
            findViewById(R.id.fl_Right).setVisibility(View.GONE);
            btn_similar.setVisibility(View.GONE);
            btn_add.setVisibility(View.VISIBLE);
        }
        if (goodsadd != null && findsimilar != null) {
            findViewById(R.id.btn_addCart).setVisibility(View.GONE);
            findViewById(R.id.btn_buy).setVisibility(View.GONE);
            findViewById(R.id.vCart).setVisibility(View.GONE);
            findViewById(R.id.vCollection).setVisibility(View.GONE);
            findViewById(R.id.fl_Right).setVisibility(View.GONE);
            btn_add.setVisibility(View.GONE);
            btn_similar.setVisibility(View.VISIBLE);
        }
        findViewById(R.id.vCollection).setOnClickListener(this);
        btn_buy = findViewById(R.id.btn_buy);
        btn_addCart = findViewById(R.id.btn_addCart);
        btn_buy.setOnClickListener(this);
        btn_addCart.setOnClickListener(this);
        btn_add.setOnClickListener(this);
        messageQbv = new QBadgeView($this);
        messageQbv.bindTarget(findViewById(R.id.fl_Right)).setBadgeGravity(Gravity.TOP | Gravity.END);
        messageQbv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent($this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                ConfigValue.hasRegisterReceiver = false;
                intent.putExtra(KEY_PAGE, 3);
                startActivity(intent);
            }
        });

        findViewById(R.id.vCart).setOnClickListener(this);
        findViewById(R.id.fl_Left).setOnClickListener(this);

        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initData();
            }
        });


        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                reloadPageTitle();
                if (canPull && Utils.isVisBottom(recyclerView)){
                    initData(false);
                }
            }
        });

    }

    private void reloadPageTitle(){
        int position = layoutManager.findFirstVisibleItemPosition();
        final String TAG = "test";

        Log.e(TAG,"position:" + position);
        if (position < 1){
            checkStatusRadio(rbGoods);
            if (getScollYDistance() <= 0) {
                //静止并处于最顶端状态
                titleView.setVisibility(View.GONE);
            } else if (getScollYDistance() > 0 && getScollYDistance() <= d100) {//滑动在0-400距离的时候
                float scale = (float) getScollYDistance() / d100;
                // 只是layout背景透明(仿知乎滑动效果)
                titleRoot.setAlpha(scale);
                titleView.setVisibility(View.VISIBLE);
            } else {
                titleView.setVisibility(View.VISIBLE);
                titleRoot.setAlpha(1f);
            }
        }else if (position < 2){
            if(getScollYDistanceFromBottom() > d100){
                checkStatusRadio(rbGoods);
                titleView.setVisibility(View.VISIBLE);
                titleRoot.setAlpha(1f);
            }else{
                checkStatusRadio(rbEvaluate);
                titleView.setVisibility(View.VISIBLE);
                titleRoot.setAlpha(1f);
            }
        }else if (position < 3){
            if (getScollYDistanceFromBottom() > d100) {
                //静止并处于最顶端状态
                checkStatusRadio(rbEvaluate);
                titleView.setVisibility(View.VISIBLE);
                titleRoot.setAlpha(1f);
            } else {
                checkStatusRadio(rbInfo);
                titleView.setVisibility(View.VISIBLE);
                titleRoot.setAlpha(1f);
            }

        }else if(position < 4){
            if (getScollYDistanceFromBottom() > d100) {
                checkStatusRadio(rbInfo);
                titleView.setVisibility(View.VISIBLE);
                titleRoot.setAlpha(1f);
            }else{
                checkStatusRadio(rbInfo);
                titleView.setVisibility(View.VISIBLE);
                titleRoot.setAlpha(1f);
            }
        }else if (position < 5){
            if (getScollYDistanceFromBottom() > d100){
                checkStatusRadio(rbInfo);
                titleView.setVisibility(View.VISIBLE);
                titleRoot.setAlpha(1f);
            } else {
                checkStatusRadio(rbRecommend);
                titleView.setVisibility(View.VISIBLE);
                titleRoot.setAlpha(1f);
            }
        }else {
            checkStatusRadio(rbRecommend);
            titleView.setVisibility(View.VISIBLE);
            titleRoot.setAlpha(1f);
        }
    }


    public int getScollYDistance() {
        int position = layoutManager.findFirstVisibleItemPosition();
        View firstVisiableChildView = layoutManager.findViewByPosition(position);
        int itemHeight = firstVisiableChildView.getHeight();
        return (position) * itemHeight - firstVisiableChildView.getTop();
    }

    public int getScollYDistanceFromBottom() {
        int position = layoutManager.findFirstVisibleItemPosition();
        View firstVisiableChildView = layoutManager.findViewByPosition(position);
        return firstVisiableChildView.getBottom();
    }


    public void initTitle() {
        ImageView ivLeft = (ImageView) titleView.findViewById(R.id.left_imbt);
        ImageView ivRight = (ImageView) titleView.findViewById(R.id.right_imbt);
        ivLeft.setImageResource(R.drawable.i_back_black);
        ivRight.setImageResource(R.drawable.i_cart_gray);
    }



    @Override
    public void initData() {
        initData(true);
    }
    public void initData(boolean refresh) {
        if (refresh){
            canPull = true;
        }
        presenter.loadGoodDetail($this, goodsID, refresh,goodsadd, new BaseView.OnLoadListener() {
            @Override
            public void onLoad(Object content) {
                Object[] param = (Object[]) content;
                switch ((int) param[0]) {
                    case CALLBACK_TYPE_RECYCLER_ADAPTER:
                        recyclerView.setAdapter(adapter = (GoodsInfoAdapter) param[1]);
                        break;
                    case CALLBACK_TYPE_GOODS_DETAIL:
                        GoodsBean.Data data = (GoodsBean.Data) param[1];
                        if (data.getIsCollect() == 1) {
                            ivCart.setImageResource(R.drawable.i_heart_red_on);
                            txtCart.setTag(R.id.decode, 1);
                        } else {
                            ivCart.setImageResource(R.drawable.i_heart_black);
                            txtCart.setTag(R.id.decode, 0);
                        }
                        break;
                    case CALLBACK_TYPE_BOOLEAN:
                        if ((boolean) param[1]) {
                            ivCart.setImageResource(R.drawable.i_heart_red_on);
                            txtCart.setTag(R.id.decode, 1);
                        } else {
                            ivCart.setImageResource(R.drawable.i_heart_black);
                            txtCart.setTag(R.id.decode, 0);
                        }
                        break;
                    case CALLBACK_TYPE_NUM:
                        if (TextUtils.isEmpty(goodsadd)) {
                            int num = (int) param[1];
                            if (num > 0) {
                                messageQbv.setBadgeText(String.valueOf(num))
                                        .setGravityOffset(10, -2, true)
                                        .setBadgeTextSize(8, true);

                                Intent mIntent = new Intent(ConfigValue.ACTION_ALTER_CARTGOODS_NUMS);
                                mIntent.putExtra("cartgoodsnum", num);
                                //发送广播
                                sendBroadcast(mIntent);
                            } else {
                                messageQbv.setBadgeText(String.valueOf(num))
                                        .setGravityOffset(2, 2, true)
                                        .setBadgeTextSize(8, true)
                                        .hide(false);
                            }
                        }else{
                            messageQbv.setBadgeText(String.valueOf(0))
                                    .setGravityOffset(2, 2, true)
                                    .setBadgeTextSize(8, true)
                                    .hide(false);
                        }
                        break;
                    case CALLBACK_TYPE_FAILURE:
                        Utils.showToast($this, "很抱歉，商品找不到了~");
                        finish();
                        break;

                    case CALLBACK_TYPE_MORE:
                        GoodsListBean.Data list = (GoodsListBean.Data) param[1];
                        adapter.loadMore(list.getList());
                        if (list.getTotalPage() < adapter.getPageNo()){
                            canPull = false;
                        }

                        break;
                }
            }
        });


    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fl_Left:
                finish();
                break;
            case R.id.btn_buy:
                CheckUtil.isRoleValid($this, new BaseView.OnLoadListener() {
                    @Override
                    public void onLoad(Object content) {
                        presenter.loadGoodAttr($this, goodsID, false, null);
                    }
                });
                break;
            case R.id.btn_addCart:
                CheckUtil.isRoleValid($this, new BaseView.OnLoadListener() {
                    @Override
                    public void onLoad(Object content) {
                        presenter.loadGoodAttr($this, goodsID, true, null);
                    }
                });
                break;
            case R.id.vCart:
                if (TextUtils.isEmpty(ConfigValue.DATA_KEY)) {
                    startActivity(new Intent($this, LoginActivity.class));
                    return;
                }

                if ((int) txtCart.getTag(R.id.decode) == 1) {
                    presenter.deleteCollectInfo($this, goodsID);
                } else {
                    presenter.addCollectInfo($this, goodsID);
                }
                break;
            case R.id.btn_add://点击增项
                presenter.loadGoodAttr($this, goodsID, true, "add");
                break;
            case R.id.btn_similar:
                presenter.loadGoodAttr($this, goodsID, true, findsimilar);
                break;
            case R.id.vCollection:
                UmengShareManager.share(this, "");
                break;

            case R.id.rbGoods:case R.id.flGoods://宝贝
                checkStatusRadio(rbGoods, 0);
                titleView.setVisibility(View.GONE);
                break;
            case R.id.rbEvaluate:case R.id.flEvaluate://评价
                checkStatusRadio(rbEvaluate,2);
                break;
            case R.id.rbInfo:case R.id.flInfo://详情
                checkStatusRadio(rbInfo,3);
                break;
            case R.id.rbRecommend:case R.id.flRecommend://推荐
                checkStatusRadio(rbRecommend,5);
                break;
        }
    }


    private void checkStatusRadio(RadioButton rb,int tag ){
        checkStatusRadio(rb);
        layoutManager.scrollToPositionWithOffset(tag,d100);
    }

    private void checkStatusRadio(RadioButton rb){
        rbGoods.setChecked(false);
        rbEvaluate.setChecked(false);
        rbRecommend.setChecked(false);
        rbInfo.setChecked(false);
        rb.setChecked(true);
        titleRoot.setAlpha(1f);
    }


    @Override
    public void showProgress() {
        super.showProgress($this);
    }

    @Override
    public void hideProgress() {
        super.hideProgress();
        refreshLayout.setRefreshing(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

}
